<?php

class ImageResize
{
    protected static $memoryLimit = '512M';

    public static function setMemoryLimit($m)
    {
        self::$memoryLimit = is_numeric($m) ? $m . 'M' : $m;
    }

    public static function simpleCopyResize($src, $dest, $maxWidth = null, $maxHeight = null, array $bgColor = [255, 255, 255])
    {
        ini_set('memory_limit', self::$memoryLimit);

        $img = null;

        switch (exif_imagetype($src)) {
            case IMAGETYPE_JPEG : case IMAGETYPE_JPEG2000 :
                $img = imagecreatefromjpeg($src);
                break;
            case IMAGETYPE_PNG :
                $img = imagecreatefrompng($src);
                break;
            case IMAGETYPE_GIF : case IMAGETYPE_ICO :
                $img = imagecreatefromgif($src);
                break;
            case IMAGETYPE_WBMP :
                $img = imagecreatefromwbmp($src);
                break;
            default : return false;
        }

        $width = $srcWidth = imagesx($img);
        $height = $srcHeight = imagesy($img);

        if ($maxWidth === null) {
            $maxWidth = $width;
        }

        if ($maxHeight === null) {
            $maxHeight = $height;
        }

        $ratio = $width / $height;

        if ($width > $maxWidth) {
            $width = $maxWidth;
            $height = $width / $ratio;
        }

        if ($height > $maxHeight) {
            $height = $maxHeight;
            $width = $height * $ratio;
        }

        $image = imagecreatetruecolor($maxWidth, $maxHeight);
        imagefill($image, 0, 0, imagecolorallocate($image, $bgColor[0], $bgColor[1], $bgColor[2]));

        $dst_x = ($maxWidth - $width) / 2;
        $dst_y = ($maxHeight - $height) / 2;

        imagecopyresampled($image, $img, $dst_x, $dst_y, 0, 0, $width, $height, $srcWidth, $srcHeight);

        imagedestroy($img);

        switch (pathinfo($dest, PATHINFO_EXTENSION)) {
            case 'jpg' : case 'jpeg' : case 'JPG' : case 'JPEG' :
                imagejpeg($image, $dest, 80);
                break;
            case 'png' : case 'PNG' :
                imagepng($image, $dest, 0);
                break;
            case 'gif' : case 'GIF' :
                imagegif($image, $dest);
                break;
            case 'bmp' : case 'BMP' : case 'wbmp' : case 'WBMP' :
                imagewbmp($image, $dest);
                break;
            default : return false;
        }

        imagedestroy($image);

        return true;
    }

}

